package com.schoolvisitors.controller.admin;

import com.alibaba.fastjson2.JSONObject;
import com.schoolvisitors.CheckPermission;
import com.schoolvisitors.common.PageResult;
import com.schoolvisitors.dto.CreateRoomDto;
import com.schoolvisitors.entity.Room;
import com.schoolvisitors.enums.PermissionEnum;
import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.service.RoomService;
import com.schoolvisitors.vo.ManageRoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/api/v1/admin")
@RestController
public class AdminRoomController {

    @Autowired
    private RoomService roomService;

    @CheckPermission(PermissionEnum.SYSTEM_ADMIN)
    @PostMapping("/createRoom")
    public ResultBody createRoom(@RequestBody CreateRoomDto createRoomDto) {
        roomService.createRoom(createRoomDto);
        return ResultBody.success();
    }

    @CheckPermission(PermissionEnum.SYSTEM_ADMIN)
    @PostMapping("/updateRoom")
    public ResultBody updateRoom(@RequestBody CreateRoomDto createRoomDto) {
        roomService.updateRoom(createRoomDto);
        return ResultBody.success();
    }

    @CheckPermission(PermissionEnum.SYSTEM_ADMIN)
    @PostMapping("/deleteRoom")
    public ResultBody deleteRoom(@RequestBody JSONObject json) {
        Long roomId = json.getLong("id");
        roomService.deleteRoom(roomId);
        return ResultBody.success();
    }


    @GetMapping("/getRooms")
    public ResultBody getRooms(
            @RequestParam("page") int page,
            @RequestParam("size") int size,
            @RequestParam(value = "number", required = false) Long number) {

        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Order.desc("id")));

        Page<Room> rooms = roomService.getRooms(pageable, number);
        Page<ManageRoomVo> voPages = rooms.map(ManageRoomVo::toVo);

        return ResultBody.success(PageResult.bind(voPages));
    }

}
